import { createApp, ref, onMounted, watch } from "https://unpkg.com/vue@3/dist/vue.esm-browser.js";
import { ElMessage } from "https://unpkg.com/element-plus";
import { Fold, Expand, House, User } from "https://unpkg.com/@element-plus/icons-vue";

const app = createApp({
    setup() {
        const isCollapsed = ref(false);
        const username = ref("Admin");
        const activeMenu = ref("/home");

        const toggleSidebar = () => {
            isCollapsed.value = !isCollapsed.value;
        };

        const handleMenuSelect = (index) => {
            activeMenu.value = index;
        };

        const goToProfile = () => {
            ElMessage.info("进入个人中心");
        };

        const logout = () => {
            localStorage.removeItem("username");
            localStorage.removeItem("password");
            localStorage.removeItem("expires");
            ElMessage.success("已退出登录");
            window.location.href = "/index.html";
        };

        const checkLoginData = () => {
            const username = localStorage.getItem("username");
            const password = localStorage.getItem("password");
            const expires = localStorage.getItem("expires");

            if (username && password && expires) {
                const expiresDate = new Date(parseInt(expires));
                const now = new Date();
                if (now < expiresDate) return { username, password };
            }
            return null;
        };

        onMounted(() => {
            const loginData = checkLoginData();
            if (loginData && loginData.username !== "") {
                ElMessage.success("欢迎 " + loginData.username);

                let currentPath = window.location.hash.replace("#", "") || "/home";
                if (currentPath === "/" || currentPath === "") {
                    activeMenu.value = "/home";
                } else {
                    activeMenu.value = currentPath;
                }
            } else {
                window.location.href = "/index.html";
            }
        });

        watch(
            () => window.location.hash,
            (newPath) => {
                activeMenu.value = newPath.replace("#", "");
            }
        );

        return {
            isCollapsed,
            username,
            activeMenu,
            toggleSidebar,
            handleMenuSelect,
            goToProfile,
            logout,
            Fold,
            Expand,
            House,
            User
        };
    }
});

export default app; // ✅ 这里导出 app
